package com.yksj.healthtalk.adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONArray;
import org.universalimageloader.core.ImageLoader;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.yksj.healthtalk.entity.BaseInfoEntity;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.utils.ViewUtils;

/**
 * 沙龙搜索和社交搜索
 * 
 * @author Administrator
 * 
 * @param <T>
 */
public class SearchAdapter<T extends BaseInfoEntity> extends BaseAdapter {
	private List<T> entities;
	private ImageLoader mImageLoader;
	private LayoutInflater inflater;
	private ViewHolder holder = null;
	private T t;
	private Context context;
	private Fragment fragment;
	private ConcurrentHashMap<String, List<MessageEntity>> messageMap;
	private int type = -1; // 如果TYPE=1 只搜索出医生， 如果TYPE=0 只搜索出客户 沙龙默认(-1)
	onClickSalonAttentionListener mAttentionListener ;
	private Drawable attenDrawable;
	private Drawable notAttenDrawable;
	private View clickView;
	private boolean isChose=false;
	private List<String> mListAdd=new ArrayList<String>(); 
	private onCheckChangeSendListener changeSendListener;
	public void setonClickSalonAttentionListener(onClickSalonAttentionListener l){
		this.mAttentionListener = l;
	}
	public interface onClickSalonAttentionListener{
		void onSalonAttentionClick(View v,GroupInfoEntity mSalonName,int positon);
	}

	public SearchAdapter(Context context, List<T> entities) {
		init(context, entities);
	}

	public interface onCheckChangeSendListener{
			void onChooseCheckChange(boolean isCheck,int position);
	}
	
	public void setOnChooseCheckListener(onCheckChangeSendListener changeSendListener){
		this.changeSendListener=changeSendListener;
	}
	
	/**
	 * 不是关注 是选择性列表
	 * @param context
	 * @param entities
	 * @param isChose
	 */
	public SearchAdapter(Context context, List<T> entities,boolean isChose) {
		init(context, entities);
		this.isChose=isChose;
	}

	public void setChangeMode(boolean isChose){
		this.isChose=isChose;
	}
	
	private void init(Context context, List<T> entities) {
		inflater = LayoutInflater.from(context);
		this.entities = entities;
		this.context = context;
		mImageLoader = ImageLoader.getInstance();
		attenDrawable = context.getResources().getDrawable(R.drawable.attention);
		notAttenDrawable = context.getResources().getDrawable(R.drawable.not_attention);
	}

	public SearchAdapter(Context context, Fragment fragment,
			List<T> entities) {
		init(context, entities);
		this.fragment = fragment;
	}
	
	public void addListEntity(List<T> entities){
		this.entities.addAll(entities);
		notifyDataSetChanged();
	}

	public void clearList(){
		this.entities.clear();
		notifyDataSetChanged();
	}
	
	public List<String> getSelectIDs(){
		return mListAdd;
	}
	
	public void selectAll(){
		mListAdd.clear();
		for (BaseInfoEntity entity : entities) {
			mListAdd.add(entity.getId());
		}
		notifyDataSetChanged();
	}
	
	public void clearSelectAll(){
		mListAdd.clear();
		notifyDataSetChanged();
	}
	
	@Override
	public int getCount() {
		return entities.size();
	}

	public void setType(int type) {
		this.type = type;
	}

	/**
	 * 构造以逗号分隔的一连串用户id
	 * @return
	 */
	public String getCusIds() {
		List<String> selectIDs = getSelectIDs();
		if(selectIDs.size() == 0)return null;
		StringBuffer buffer = new StringBuffer();
		for (String  id : selectIDs) {
			buffer.append(id);
			buffer.append(",");
		}
		int index = buffer.lastIndexOf(",");
		return buffer.substring(0,index);
	}
	
	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	// 获取翻页的标记
	public String getPageFlagMark(boolean isFristPage, Object t) {
		if (t instanceof CustomerInfoEntity) {
			if (entities != null && entities.size() > 0 && !isFristPage) {
				return ((CustomerInfoEntity) entities.get(entities.size() - 1)).getFlag();
			} else {
				return "-100000";
			}
		} else if(t instanceof GroupInfoEntity){
			if (entities != null && entities.size() > 0 && !isFristPage) {
				return ((GroupInfoEntity) entities.get(entities.size() - 1)).getFlag();
			} else {
				return "";
			}
		}else if(type!=-1){
			if (entities != null && entities.size() > 0 && !isFristPage) {
				return ((CustomerInfoEntity) entities.get(entities.size() - 1)).getFlag();
			} else {
				return "-100000";
			}
		}else{
			if (entities != null && entities.size() > 0 && !isFristPage) {
				return ((GroupInfoEntity) entities.get(entities.size() - 1)).getFlag();
			} else {
				return "";
			}
		}
	}

	// 硬性排序标记
	public String getFlagPlacingMark(boolean isFristPage, Object t) {
		if (t instanceof GroupInfoEntity) {
			if (entities != null && entities.size() > 0 && !isFristPage) {
				return ((GroupInfoEntity) entities.get(entities.size() - 1))
						.getFlagPlacing();
			} else {
				return "-100000";
			}
		} else {
			return "";
		}
	}


	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		System.out.println(position+"");
		t = entities.get(position);
		if (convertView == null) {
			holder = new ViewHolder();
			if (t instanceof GroupInfoEntity) {
				convertView = inflater.inflate(R.layout.grouplist_item1, null);
				holder.charge = (ImageView) convertView.findViewById(R.id.money);
				holder.level = (ImageView) convertView.findViewById(R.id.levl);
				holder.doctor = (ImageView) convertView.findViewById(R.id.doctor_salon);
				holder.describe = (TextView) convertView.findViewById(R.id.note);
				holder.attention_salon_iv = (ImageView) convertView.findViewById(R.id.attention_salon_iv);
				holder.choose=(CheckBox)convertView.findViewById(R.id.check1);
			} else if (type == 0) {// 社交场搜索出来的
				convertView = inflater.inflate(R.layout.friendlist_item1, null);
				convertView.findViewById(R.id.choose).setVisibility(View.GONE);
				holder.sex = (ImageView) convertView.findViewById(R.id.head_sex);
				holder.doctor = (ImageView) convertView.findViewById(R.id.levl);
				holder.describe = (TextView) convertView.findViewById(R.id.note);
				holder.attention_salon_iv = (ImageView) convertView.findViewById(R.id.attention);
				holder.choose=(CheckBox)convertView.findViewById(R.id.check1);
				
			} else if (type == 1) {// 医生馆搜索出来的
				convertView = inflater.inflate(R.layout.doctor_item1, null);
				holder.doctor = (ImageView) convertView.findViewById(R.id.v);
				holder.title_departments = (TextView) convertView.findViewById(R.id.title_departments);
				holder.hospital = (TextView) convertView.findViewById(R.id.hospital);
				holder.special = (TextView) convertView.findViewById(R.id.special);
				holder.choose=(CheckBox)convertView.findViewById(R.id.check1);
				holder.attention_salon_iv = (ImageView) convertView.findViewById(R.id.attention_salon_iv);
			}
			holder.header = (ImageView) convertView.findViewById(R.id.head_image);
			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.message = (TextView) convertView.findViewById(R.id.item_dele);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		messageMap = HTalkApplication.getAppData().messageCllection;
		// 消息

		if (messageMap.containsKey(t.getId())
				&& messageMap.get(t.getId()).size() != 0) {
			holder.message.setVisibility(View.VISIBLE);
			int size=messageMap.get(t.getId()).size();
			String readCount=size >100 ? "99+":String.valueOf(size);
			holder.message.setText(readCount);
		} else {
			holder.message.setVisibility(View.GONE);
		}
		holder.name.setText(t.getName());
		// 只有社交场和沙龙才有describe
		if (type != 1) {
			holder.describe.setText(t.getDescription());
		}
		
		if(type==-1)
			holder.describe.setText(((GroupInfoEntity) t).getRecordDesc());
		
		if (fragment == null && context instanceof OnClickListener) {
			holder.header.setOnClickListener((OnClickListener) context);
		} else if (fragment != null && fragment instanceof OnClickListener) {
			holder.header.setOnClickListener((OnClickListener) fragment);
		}
		holder.header.setTag(position);
		if (t instanceof GroupInfoEntity) {
			final GroupInfoEntity entity = (GroupInfoEntity) t;
			// 头像
			mImageLoader.displayImage("4",entity.getNormalHeadIcon(),holder.header);
			// 收费
			ViewUtils.setGone(holder.charge, !entity.isCharge());
			
			// 等级
			if (NumberUtils.isNumber(entity.getGroupLevel())) {
				int i = Integer.valueOf(entity.getGroupLevel());
				if (i != 0) {
					holder.level.getDrawable().setLevel(i);
				}
				ViewUtils.setGone(holder.level, !(i != 0));
			} else {
				holder.level.setVisibility(View.GONE);
			}
			
			// 是否是医师沙龙
			ViewUtils.setGone(holder.doctor, !entity.isSalon());
			//关注状态 1已收藏 
			if (entity.isSalonAttention()) {
				holder.attention_salon_iv.setImageResource(R.drawable.not_attention);
			}else {
				holder.attention_salon_iv.setImageResource(R.drawable.attention);
			}
		
			holder.attention_salon_iv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
					if (mAttentionListener != null) {
						mAttentionListener.onSalonAttentionClick(holder.attention_salon_iv, entity, position);
					}
				}
			});
			
			//是否是选择状态
			ViewUtils.setGone(holder.choose, !isChose);
			ViewUtils.setGone(holder.attention_salon_iv, isChose);
			
			
			holder.choose.setChecked(mListAdd.contains(entity.getId()));
			holder.choose.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if(mListAdd.size()==entities.size() && changeSendListener!=null)
						changeSendListener.onChooseCheckChange(isChecked, position);
					
					if(isChecked){
						if(!mListAdd.contains(entity.getId())) mListAdd.add(entity.getId());
					}else{
						if(mListAdd.contains(entity.getId())) mListAdd.remove(entity.getId());
					}
					
				}
			});
		} else if (t instanceof CustomerInfoEntity) {
			final CustomerInfoEntity entity = (CustomerInfoEntity) t;
			// 是否是医生
			ViewUtils.setGone(holder.doctor, !entity.isDoctor());
			// 性别
			mImageLoader.displayImage(entity.getSex(),entity.getNormalHeadIcon(),holder.header);
			if (type == 0) {
				holder.sex.getDrawable().setLevel(Integer.valueOf(entity.getSex()));
			} else if (entity.isDoctor()) {
				// 职称/科室
				if (TextUtils.isEmpty(entity.getOfficeName1())) {
					holder.title_departments.setText(entity.getDoctorTitle());
				} else {
					holder.title_departments.setText(entity.getDoctorTitle()
							+ "/" + entity.getOfficeName1());
				}
				// 医院
				holder.hospital.setText(entity.getHospital());
				// 专长
				holder.special.setText(entity.getSpecial());
			}
			
			if (entity.getIsAttentionFriend() !=0 && entity.getIsAttentionFriend() !=2) {
				holder.attention_salon_iv.setImageDrawable(notAttenDrawable);
			}else {
				holder.attention_salon_iv.setImageDrawable(attenDrawable);
			}
			
			//是自己 不显示关注按钮
			ViewUtils.setInvisible(holder.attention_salon_iv, entity.getId().equals(SmartFoxClient.getLoginUserId()));
			
			//点击取消和添加关注安妮
			holder.attention_salon_iv.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (attentionListener != null) {
						attentionListener.onClickFriendAttention(entity.getIsAttentionFriend() ,entity , position );
					}
						setClickView(v);
				}
			});
			//是否是选择状态
			ViewUtils.setGone(holder.attention_salon_iv, isChose);
			ViewUtils.setGone(holder.choose, !isChose);
			
			holder.choose.setChecked(mListAdd.contains(entity.getId()));
			holder.choose.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if(mListAdd.size()==entities.size()&&changeSendListener!=null)
						changeSendListener.onChooseCheckChange(isChecked, position);
					
					if(isChecked){
						if(!mListAdd.contains(entity.getId())) mListAdd.add(entity.getId());
					}else{
						if(mListAdd.contains(entity.getId())) mListAdd.remove(entity.getId());
					}
					
				}
			});
		}
		return convertView;
	}
	
	public void setClickView(View v){
		this.clickView = v;
	}
	
	public View getClickView(){
		return clickView;
	}
	
	
	onClickFriendAttentionListener attentionListener;
	
	
	public interface onClickFriendAttentionListener{
		void onClickFriendAttention(int attentioned,CustomerInfoEntity entity , int positon);
	}
	
	
	public void setonClickFriendAttentionListener(onClickFriendAttentionListener attentionListener){
		this.attentionListener = attentionListener;
	};
	
	
	
	class ViewHolder {
		public CheckBox choose;
		ImageView attention_salon_iv;
		ImageView header;
		TextView describe;
		TextView message;
		ImageView level;
		ImageView charge;
		ImageView doctor;
		TextView name;
		ImageView sex;

		TextView title_departments;
		TextView hospital;
		TextView special;
	}

}
